package com.ruoyi.framework.config;

import com.ruoyi.common.core.domain.model.XcxUser;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.util.HashMap;
import java.util.Map;

public class XcxAuthenticationProvider implements AuthenticationProvider {

    private UserDetailsService userDetailsService;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        XcxAuthenticationToken xcxAuthenticationToken = (XcxAuthenticationToken) authentication;
        String openId = xcxAuthenticationToken.getOpenId();


        // 判断验证码是否一致
        if (StringUtils.isBlank(openId)) {
            throw new BadCredentialsException("身份获取错误!");
        }
        XcxUser loadedUser = (XcxUser) userDetailsService.loadUserByUsername(openId);
        if (loadedUser == null) {
            throw new UsernameNotFoundException("用户不存在!");
        } else {
            XcxAuthenticationToken result = new XcxAuthenticationToken(loadedUser, null, null);
            return result;
        }
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return XcxAuthenticationToken.class.isAssignableFrom(authentication);
    }

    public void setUserDetailsService(UserDetailsService userDetailsService) {
        this.userDetailsService = userDetailsService;
    }
}
